package com.example.rabbit.demo.dlx;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: rabbit-demo
 * @description:
 * @author: zhaoliang
 * @create: 2019-12-30 13:31
 */
public class Consumer {

    public static void main(String[] args) throws Exception {
        //1.创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.200.128");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");

        //2.通过连接工厂创建连接
        Connection connection = connectionFactory.newConnection();
        //3.通过connection创建一个channel
        Channel channel = connection.createChannel();
        //4.声明（创建）一个队列
        //参数1：队列名称；参数2：是否持久化；参数3：是否独占；参数4：是否自动删除；参数5：扩展参数
        String exchangeName="test_dlx_exchange";
        String exchangeType="topic";
        String routingKey="dlx.*";
        String queueName = "test_dlx_queue";

        //声明一个交换机
        channel.exchangeDeclare(exchangeName,exchangeType,true,false,false,null);
        //arguments属性，要设置到声明队列上
        Map<String,Object> arguments = new HashMap<>();
        arguments.put("x-dead-letter-exchange","dlx.exchange");
        channel.queueDeclare(queueName,true,false,false,arguments);

        //要进行死信队列声明
        channel.exchangeDeclare("dlx.exchange","topic",true,false,null);
        channel.queueDeclare("dlx.queue",true,false,false,null);
        channel.queueBind("dlx.queue","dlx.exchange","#");

        //建立一个绑定关系
        channel.queueBind(queueName,exchangeName,routingKey);

        //7.手工签收必须要关闭autoAck=false
        channel.basicConsume(queueName,false,new MyConsumer(channel));

    }
}
